package cn.xinfei.xdecision.data.alarm;

import cn.xinfei.xdecision.data.core.frame.retry.HttpClientManage;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.util.Base64;

public class DingDingMessageUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(DingDingMessageUtil.class);

    public static void sendTextMessage(String accessToken, String secret, String msg) {
        HttpClientManage client;
        try {
            long timestamp = System.currentTimeMillis();
            String sign = getSign(secret, timestamp);
            client = HttpClientManage.getOkHttpClientManage(buildReqUrl(accessToken, timestamp, sign));
            JSONObject request = new JSONObject();
            request.put("msgType", "text");
            request.put("text", new JSONObject().fluentPut("content", msg));
            client.post(JSONObject.toJSONString(request), HttpClientManage.MEDIATYPE_JSON);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("钉钉告警异常", e);
        }
    }


    public static void post(String url, JSONObject request) {
        HttpClientManage client;
        try {
            client = HttpClientManage.getOkHttpClientManage(url);
            client.post(JSONObject.toJSONString(request), HttpClientManage.MEDIATYPE_JSON);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("外部告警异常 url = {}", url, e);
        }
    }

    private static String getSign(String secret, long timestamp) {
        try {
            String stringToSign = timestamp + "\n" + secret;
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
            return URLEncoder.encode(new String(Base64.getEncoder().encode(signData)), "UTF-8");
        } catch (Exception e) {
            throw new RuntimeException("钉钉发送消息签名失败");
        }
    }

    private static String buildReqUrl(String accessToken, Long timestamp, String sign) {
        return "https://oapi.dingtalk.com/robot/send?access_token=" + accessToken
                + "&timestamp=" + timestamp
                + "&sign=" + sign;
    }
}

